package cn.itcast.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 虎哥
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取request对象
        ServerHttpRequest request = exchange.getRequest();
        // 2.获取用户请求参数中的 access-token 参数
        MultiValueMap<String, String> params = request.getQueryParams();
        String token = params.getFirst("access-token");
        // 3.判断是否为"admin"
        if ("admin".equals(token)) {
            // 5.如果是，证明已经登录，放行请求
            return chain.filter(exchange);
        }
        // 4.如果不是，证明未登录，拦截请求
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应的状态码, 401代表未登录！
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 设置请求处理到此结束，被拦截了。
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
